<?php

namespace app\controllers\admin\uni\product;

use app\controllers\admin\base\AdminController;
use app\models\product\Product;
use app\models\product\ProductSku;
use app\models\product\ProductSku as Model;
use app\models\product\ProductSkuName;
use app\models\product\ProductSkuValue;
use app\models\ZColor;
use app\models\ZSize;
use yii\helpers\ArrayHelper;

class SkuController extends AdminController
{
    public function actionList()
    {
        $name = $this->post('name');
        $id = $this->post('id');

        $product_id = $this->post('product_id');

        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $sort = $this->post('sort');

        $query = Model::find()
            ->where(['!=', 'status', Model::$statusMapping['DELETE']])
            ->andWhere(['product_id' => $product_id])
            ->with(['image']);

        if ($sort) {
            $prop = substr($sort, 0, 1);
            $prop = $prop == '-' ? SORT_DESC : SORT_ASC;
            $order = substr($sort, 1);
            $query->orderBy([$order => $prop]);
        } else {
            $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC]);
        }

        if ($id) {
            $query->andWhere(['id' => $id]);
        }
        if ($name) {
            $query->andWhere(['like', 'name', $name]);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            $item['list'] = Model::skuList($item['sku_list']);
        }

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
        ]);

    }

    public function actionEdit()
    {
        $data = $this->post();

        try {
            if (isset($data['id']) && $data['id'] > 0) {
                $model = Model::findOne(['id' => $data['id']]);
                if (!$model) {
                    return $this->fail('操作失败');
                }
            } else {
                $model = new Model();
            }
            $data = ['ProductSku' => $data];
            if ($model->load($data) && $model->save()) {

                return $this->success($model, '操作成功');
            }
            // var_dump($model->getErrors());
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function actionView()
    {
        $id = $this->post('id');
        $model = Model::find()
            ->where(['id' => $id])
            ->with(['image'])
            ->asArray()
            ->one();

        if ($model) {
            return $this->success($model);
        }

        return $this->fail('不存在该规格');
    }

    private function _sku($product_id)
    {
        // $has = ProductSkuName::find()
        //     ->where(['product_id' => $product_id])
        //     ->andWhere(['name' => '码段'])
        //     ->count();
        // if ($has) {
        //     return;
        // }

        // todo 处理码段
        // skuName, => values
        $names = [
            [
                'name' => '颜色',
                'values' => ZColor::find()
                    ->select('id, name as value')
                    ->where(['status' => 1])
                    ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
                    ->asArray()
                    ->all(),
            ],
            [
                'name' => '码段',
                'values' => ZSize::find()
                    ->select(['id', "CONCAT(start, ' - ', end) as value", 'start', 'end'])
                    ->where(['status' => 1])
                    ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
                    ->asArray()
                    ->all(),
            ]
        ];

        // var_dump($names);exit;

        foreach ($names as $item) {
            $sku_name = ProductSkuName::find()
                ->where(['product_id' => $product_id])
                ->andWhere(['name' => $item['name']])
                ->one();
            if (!$sku_name) {
                $sku_name = new ProductSkuName();
                $sku_name->product_id = $product_id;
                $sku_name->name = $item['name'];
                $sku_name->save();
            }
            foreach ($item['values'] as $value) {
                $sku_value = ProductSkuValue::find()
                    ->where(['product_sku_name_id' => $sku_name->id])
                    ->andWhere(['value' => $value['value']])
                    ->one();
                if (!$sku_value) {
                    $sku_value = new ProductSkuValue();
                    $sku_value->product_sku_name_id = $sku_name->id;
                    $sku_value->value = $value['value'];
                    $sku_value->save();
                }
            }
        }
    }

    public function actionViewProduct()
    {
        $product_id = $this->post('product_id');

        $this->_sku($product_id);

        $model = Product::find()
            ->where(['id' => $product_id])
            ->with(['sku', 'skuName', 'skuName.values', 'sku.image'])
            ->asArray()
            ->one();

        if ($model) {

            // todo 这里处理码段
            // $model['skuName'] = [
            //     [
            //         'name' => '颜色',
            //         'values' => ZColor::find()
            //             ->select('id, name as value')
            //             ->where(['status' => 1])
            //             ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
            //             ->asArray()
            //             ->all(),
            //     ],
            //     [
            //         'name' => '码段',
            //         'values' => ZSize::find()
            //             ->select(['id', "CONCAT(start, ' - ', end) as value", 'start', 'end'])
            //             ->where(['status' => 1])
            //             ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
            //             ->asArray()
            //             ->all(),
            //     ]
            // ];


            return $this->success($model);
        }

        return $this->fail('商品错误');
    }

    // 新的sku编辑
    public function actionEditSku()
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $product_id = $this->post('product_id');
            $data = $this->post('list', []);

            // var_dump($product_id, $data);

            // 需要删除不符合的
            $_ids = ArrayHelper::getColumn($data, '_id');
            $no = Model::find()
                ->where(['product_id' => $product_id])
                ->andWhere(['not in', 'sku_list', $_ids])
                ->select(['id'])
                ->column();
            if ($no) {
                Model::updateAll(['status' => 0], ['id' => $no]);
            }

            foreach ($data as $sku) {
                $model = Model::find()
                    ->where(['product_id' => $product_id])
                    ->andWhere(['sku_list' => $sku['_id']])
                    ->one();
                if (!$model) {
                    $model = new Model();
                    $model->sku_list = $sku['_id'];
                    $model->product_id = $product_id;
                }
                $model->status = intval($sku['status']);
                $model->price = $sku['price'];
                $model->self_cost = $sku['cost'];
                $model->stock = $sku['stock'];
                $model->sort = $sku['sort'];
                // $model->image_id = intval($sku['image']);
                // $model->sn = $sku['sn'];
                $model->save();
            }
            $transaction->commit();
            return $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }
    }

    // sku 图片上传
    public function actionUploadImage()
    {
        $id = $this->post('id');
        $image_id = $this->post('image_id');
        $product_id = $this->post('product_id');

        // var_dump($id, $image_id, $product_id);

        $model = Model::find()
            ->where(['product_id' => $product_id])
            ->andWhere(['sku_list' => $id])
            ->one();

        if (!$model) {
            $model = new Model();
            $model->product_id = $product_id;
            $model->sku_list = $id;
        }

        if ($model) {
            $model->image_id = $image_id;
            $model->save();

            return $this->success();
        }
    }

    public function actionRemove()
    {
        $id = $this->post('id');

        try {
            $model = Model::findOne(['id' => $id]);
            $model->status = Model::$statusMapping['DELETE'];
            $model->save();
            return $this->success($model, '删除成功');
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function actionStatusList()
    {
        return $this->success(Model::statusList());
    }

    public function actionChangeStatus()
    {
        $id = intval($this->post('id'));
        $status = intval($this->post('status'));

        try {
            $model = Model::findOne(['id' => $id]);
            $model->status = $status;
            $model->save();

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('操作错误: ' . $e->getMessage());
        }
    }

    public function actionChangeSort()
    {
        $id = intval($this->post('id'));
        $sort = intval($this->post('sort'));

        try {
            $model = Model::findOne(['id' => $id]);
            $model->sort = $sort;
            $model->save();

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('操作错误: ' . $e->getMessage());
        }
    }

    public function actionBatchRemove()
    {
        $ids = $this->post('ids');

        try {
            Model::updateAll(['status' => Model::$statusMapping['DELETE']], ['id' => $ids]);

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('删除错误: ' . $e->getMessage());
        }
    }
}